package ke07.pm.reihe3;

import java.util.ArrayList;
import java.util.Iterator;
import ke07.pm.template.HundredItemBag;

public class HundredItemBagDrei<T> implements HundredItemBag<T>
{
    private ArrayList<T> items = new ArrayList<T>();
    
    /**
     * @return The total amount of stored items in this bag.
     */
    public int size()
    {
        return items.size();
    }

    /**
     * Puts an object to the Bag.
     * 
     * @param obj
     *            the object to store in the Bag.
     * @return true if, and only if, an object equal to the given object was
     *         already contained in the Bag before the given object was added.
     * @throws NullPointerException
     *             if the given object is the null reference.
     */
    public boolean add(T obj)
    {
    	if(obj==null){
    		throw new NullPointerException();
    	}
    	else if(items.contains(obj)){
    		items.add(obj);
    	return true;}
    	
    	else {
    		items.add(obj);
    	return false;}
    	
    }

    /**
     * Removes the first occurrence of an object from the Bag.
     * 
     * @param obj
     *            the object to remove.
     * @return true if, and only if, {@link #count(T)} would return 0 after
     *         calling this method, i.e. the given object was the last one of
     *         its kind in the bag or there was nothing to remove.
     * @throws IllegalArgumentException
     *             if the given object is the null reference.
     */
    public boolean remove(T obj)
    {

    	if(obj==null){
    		throw new IllegalArgumentException();
    	}
    	else if(this.count(obj)==0 || this.count(obj)==1){
    		items.remove(obj);    	
    	return true;}
    	
    	else{
    		items.remove(obj);
        return false;}

    }

    /**
     * @param obj
     *            the object to count.
     * @return Amount of occurrences of this object in the Bag, as defined by
     *         equals method.
     */
    public int count(T obj)
    {
        int result = 0;
        Iterator<T> iterator = items.iterator();

        while ( iterator.hasNext() )
        {
            if ( iterator.next().equals(obj) )
                result++;
        }

        return result;
    }

    /**
     * @param obj
     *            the object to check for.
     * @return Whether the given object is contained in the Bag.
     */
    public boolean contains(T obj)
    {
        if ( items.contains(obj) )
            return true;
        else
            return false;
    }

    /**
     * @return A copy of all elements in this Bag as an array of T with
     *         {@link #size()} entries.
     */
    public T[] toArray()
    {
        // T[] result = null;
        return (T[]) items.toArray();
    }
}
